<?php
/*
 module:		红心充值订单
 create_time:	2022-04-05 20:58:19
 author:   陕西格创
 contact:
*/

namespace app\api\controller;

use app\api\model\Member as MemberModel;
use app\api\model\ZhPayLog as ZhPayLogModel;
use app\api\service\PaymentService;
use app\api\service\ZhGiftOrderService;
use app\api\model\ZhGiftOrder as ZhGiftOrderModel;
use app\backend\model\SysSite as SysSiteModel;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use app\api\model\ZhVirtualCurrency as ZhVirtualCurrencyModel;

class ZhGiftOrder extends Common {
    
    
    /**
     * @api {get} /ZhGiftOrder/index 01、首页数据列表
     * @apiGroup ZhGiftOrder
     * @apiVersion 1.0.0
     * @apiDescription  首页数据列表
     
     * @apiHeader {String} Authorization 用户授权token
     * @apiHeaderExample {json} Header-示例:
     * "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"
     
     * @apiParam (输入参数：) {int}     		[limit] 每页数据条数（默认20）
     * @apiParam (输入参数：) {int}     		[page] 当前页码
     * @apiParam (输入参数：) {string}		[order_sn] 订单号
     * @apiParam (输入参数：) {int}			[status] 订单状态 已支付|1|success,待支付|0|danger,已取消|2|info
     
     * @apiParam (失败返回参数：) {object}     	array 返回结果集
     * @apiParam (失败返回参数：) {string}     	array.status 返回错误码 201
     * @apiParam (失败返回参数：) {string}     	array.msg 返回错误消息
     * @apiParam (成功返回参数：) {string}     	array 返回结果集
     * @apiParam (成功返回参数：) {string}     	array.status 返回错误码 200
     * @apiParam (成功返回参数：) {string}     	array.data 返回数据
     * @apiParam (成功返回参数：) {string}     	array.data.list 返回数据列表
     * @apiParam (成功返回参数：) {string}     	array.data.count 返回数据总数
     * @apiSuccessExample {json} 01 成功示例
     * {"status":"200","data":""}
     * @apiErrorExample {json} 02 失败示例
     * {"status":" 201","msg":"查询失败"}
     */
    function index(){
        $wxapp_id = $this->request->get('wxapp_id');
        $uId      = $this->request->uid;
        if(!$wxapp_id){
            return $this->ajaxReturn($this->errorCode,'缺少平台参数');
        }
        $wxSetting    = SysSiteModel::where('wxapp_id',$wxapp_id)->find();
        if(!$wxSetting){
            return $this->ajaxReturn($this->errorCode,'平台参数未配置');
        }
        
        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if(!$user){
            return $this->ajaxReturn($this->errorCode,'未知用户');
        }
        $limit  = $this->request->get('limit', 20, 'intval');
        $page   = $this->request->get('page', 1, 'intval');
        
        $where = [];
        $where['wxapp_id'] = $wxapp_id;
        $where['u_id']     = $uId;
        $where['status']   = 1;
        
        $field = '*';
        $orderby = 'id desc';
        
        $res = ZhGiftOrderService::indexList(formatWhere($where),$field,$orderby,$limit,$page);
        foreach ($res['list'] as &$v){
            $v['title']      = '成功充值' . $v['gift_b_price'] . '元';
            $v['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
        }
        unset($v);
        return $this->ajaxReturn($this->successCode,'返回成功',htmlOutList($res));
    }
    
    /**
     * @api {post} /ZhGiftOrder/add 02、添加
     * @apiGroup ZhGiftOrder
     * @apiVersion 1.0.0
     * @apiDescription  添加
     
     * @apiHeader {String} Authorization 用户授权token
     * @apiHeaderExample {json} Header-示例:
     * "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"
     * @apiParam (输入参数：) {string}			wxapp_id 平台id
     * @apiParam (输入参数：) {string}			order_sn 订单号
     * @apiParam (输入参数：) {int}				status 订单状态 已支付|1|success,待支付|0|danger,已取消|2|info
     * @apiParam (输入参数：) {int}				u_id 用户id
     * @apiParam (输入参数：) {int}				gift_b_num 红心数量
     * @apiParam (输入参数：) {string}			gift_b_price 红心价格
     
     * @apiParam (失败返回参数：) {object}     	array 返回结果集
     * @apiParam (失败返回参数：) {string}     	array.status 返回错误码  201
     * @apiParam (失败返回参数：) {string}     	array.msg 返回错误消息
     * @apiParam (成功返回参数：) {string}     	array 返回结果集
     * @apiParam (成功返回参数：) {string}     	array.status 返回错误码 200
     * @apiParam (成功返回参数：) {string}     	array.msg 返回成功消息
     * @apiSuccessExample {json} 01 成功示例
     * {"status":"200","data":"操作成功"}
     * @apiErrorExample {json} 02 失败示例
     * {"status":" 201","msg":"操作失败"}
     */
    function add(){
        $wxapp_id = $this->request->post('wxapp_id');
        $uId      = $this->request->uid;
        $id       = $this->request->post('id','','serach_in');// 红心菜单id
        $num      = $this->request->post('num','','serach_in');// 自定义购买红心数量
        $type     = $this->request->post('type','wx','serach_in');
        if(!$wxapp_id){
            return $this->ajaxReturn($this->errorCode,'缺少平台参数');
        }
        $wxSetting    = SysSiteModel::where('wxapp_id',$wxapp_id)->find();
        if(!$wxSetting){
            return $this->ajaxReturn($this->errorCode,'平台参数未配置');
        }
        
        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if(!$user){
            return $this->ajaxReturn($this->errorCode,'未知用户');
        }
        if($num && $id){
            return $this->ajaxReturn($this->errorCode,'信息参数错误');
        }
        if(!$num && !$id){
            return $this->ajaxReturn($this->errorCode,'缺少信息参数');
        }
        if($id && !$num){
            $giftBData = ZhVirtualCurrencyModel::where(['wxapp_id'=> $wxapp_id,'id'=> $id])->find();
            if(!$giftBData){
                return $this->ajaxReturn($this->errorCode,'信息参数错误');
            }else {
                $num = $giftBData['name'];
            }
        }
        $total_price = round($num/$wxSetting['proportion'],2);
        $data = [
            'wxapp_id'     => $wxapp_id,
            'order_sn'     => $uId . '0' . $wxapp_id . time() . rand(100,999),
            'status'       => 0,
            'u_id'         => $uId,
            'gift_b_num'   => $num,
            'gift_b_price' => $total_price,
            'createtime'   => time()
        ];
        $ZhGiftOrderId = ZhGiftOrderModel::insertGetId($data);
        if($ZhGiftOrderId){
            $ZhGiftOrderData = ZhGiftOrderModel::where(['wxapp_id'=>$wxapp_id,'id'=>$ZhGiftOrderId])->find();
            if($ZhGiftOrderData){
                $arr = [
                    'wxapp_id'     => $ZhGiftOrderData['wxapp_id'],
                    'uid'          => $ZhGiftOrderData['u_id'],
                    'order_sn'     => $ZhGiftOrderData['order_sn'],
                    'price'        => $ZhGiftOrderData['gift_b_price'],
                    'status'       => 0,
                    'type'         => '购买红心',
                    'gift_b_num'   => $ZhGiftOrderData['gift_b_num'],
                    'gift_b_price' => $ZhGiftOrderData['gift_b_price'],
                    'create_time'  => date('Y-m-d H:i:s',time())
                ];
                ZhPayLogModel::insert($arr);
                try {
                    $notify_url = 'http://' . $_SERVER['HTTP_HOST'] .'/api/ZhGiftOrder/payResult/wxapp_id/'.$wxapp_id;
                    if($type == 'wx'){
                        $trade_type = 'JSAPI';
                    }elseif ($type == 'app'){
                        $trade_type = 'APP';
                    } elseif ($type == 'H5'){
                        $trade_type = 'MWEB';
                    }elseif ($type == 'H5-wx'){
                        $trade_type = 'JSAPI';
                        $user['openid'] = $user['official_account_openid'];
                    }
                    
                    $js_pay = PaymentService::instance($wxapp_id,$type)->create($user['openid'], $ZhGiftOrderData['order_sn'], $ZhGiftOrderData['gift_b_price'], '购买红心', ['notify_url' => $notify_url],$trade_type);
                    return $this->ajaxReturn($this->successCode, '操作成功', ['order' => $ZhGiftOrderData['order_sn'], 'paydata' => $js_pay]);
                } catch (\Exception $e) {
                    return $this->ajaxReturn($this->errorCode, $e->getMessage());
                }
            }
        }
    }
    
    /**
     * @api {get} /ZhGiftOrder/view 03、查看详情
     * @apiGroup ZhGiftOrder
     * @apiVersion 1.0.0
     * @apiDescription  查看详情
     
     * @apiParam (输入参数：) {string}     		id 主键ID
     * @apiParam (输入参数：) {string}     		800px 主键ID
     * @apiParam (输入参数：) {string}     		550px 主键ID
     
     * @apiHeader {String} Authorization 用户授权token
     * @apiHeaderExample {json} Header-示例:
     * "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"
     
     * @apiParam (失败返回参数：) {object}     	array 返回结果集
     * @apiParam (失败返回参数：) {string}     	array.status 返回错误码 201
     * @apiParam (失败返回参数：) {string}     	array.msg 返回错误消息
     * @apiParam (成功返回参数：) {string}     	array 返回结果集
     * @apiParam (成功返回参数：) {string}     	array.status 返回错误码 200
     * @apiParam (成功返回参数：) {string}     	array.data 返回数据详情
     * @apiSuccessExample {json} 01 成功示例
     * {"status":"200","data":""}
     * @apiErrorExample {json} 02 失败示例
     * {"status":"201","msg":"没有数据"}
     */
    function view(){
        $data['800px'] = $this->request->get('800px','','serach_in');
        $data['550px'] = $this->request->get('550px','','serach_in');
        $field='id,wxapp_id,order_sn,status,u_id,gift_b_num,gift_b_price,createtime';
        $res  = checkData(ZhGiftOrderModel::field($field)->where($data)->find());
        return $this->ajaxReturn($this->successCode,'返回成功',$res);
    }
    
    
    // 支付回调
    public function payResult()
    {
        $wxapp_id = input('wxapp_id');
        trace('进入回调'.$wxapp_id, 'notify_' . date('Y_m_d'));
        $app      = PaymentService::instance($wxapp_id)::getPayApp();
        $response = $app->handlePaidNotify(function ($message, $fail) use($wxapp_id) {
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            trace($message, 'notify_' . date('Y_m_d'));
            $order = ZhGiftOrderModel::where(['order_sn' => $message['out_trade_no']])->find();
            if (!$order || $order->status == 1) { // 如果订单不存在 或者 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    // 修改红心充值订单和充值记录状态
                    ZhGiftOrderModel::where([
                        'order_sn' => $message['out_trade_no'],
                        'wxapp_id' => $wxapp_id
                    ])->update(['status'=>1]);
                    ZhPayLogModel::where([
                        'order_sn' => $message['out_trade_no'],
                        'wxapp_id' => $wxapp_id
                    ])->update(['status'=>1,'wx_order_sn'=>$message['transaction_id']]);
                    // 更新用户红心余额
                    $ZhMemberData = MemberModel::where([
                        'uid'      => $order['u_id'],
                        'wxapp_id' => $wxapp_id
                    ])->find();
                    if($ZhMemberData){
                        $virtualCurrencyBalance = $ZhMemberData['virtual_currency_balance'] ? $ZhMemberData['virtual_currency_balance'] : 0;
                        $newNum = round($virtualCurrencyBalance + $order['gift_b_num']);
                        MemberModel::where([
                            'uid'      => $order['u_id'],
                            'wxapp_id' => $wxapp_id
                        ])->update(['virtual_currency_balance'=>$newNum]);
                    }
                    // 分销（上级和红娘只能存在一个，上级存在就给上级分销，红娘存在就给红娘）
                    $pId = 0;
                    $SysSiteData = SysSiteModel::where('wxapp_id',$wxapp_id)->find();
                    if($ZhMemberData['p_id'] && !$ZhMemberData['matchmaker_id']){
                        $pId = $ZhMemberData['p_id'];
                        $biLi = round($SysSiteData['superior_take_prop'] / 100,2) ? round($SysSiteData['superior_take_prop'] / 100,2) : 0;
                    }elseif (!$ZhMemberData['p_id'] && $ZhMemberData['matchmaker_id']){
                        $pId = $ZhMemberData['matchmaker_id'];
                        $biLi = round($SysSiteData['matchmaker_take_prop'] / 100,2) ? round($SysSiteData['matchmaker_take_prop'] / 100,2) : 0;
                    }
                    
                    if($pId){
                        $PMemberData = MemberModel::where([
                            'uid'      => $pId,
                            'wxapp_id' => $wxapp_id
                        ])->find();
                        $PBalance = $PMemberData['balance'] ? $PMemberData['balance'] : 0;
                        $newPBalance = round($PBalance + $order['gift_b_price'] * $biLi,2);
                        MemberModel::where([
                            'uid'      => $pId,
                            'wxapp_id' => $wxapp_id
                        ])->update(['balance'=> $newPBalance]);
                    }
                    
                    // 用户支付失败
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            return true; // 返回处理完成
        });
        return $response->send(); // return $response;
    }
    
    
    
}

